package com.yorge.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
@Slf4j
public class MessageRabbitMQ {
    @Resource
    AmqpTemplate amqpTemplate;

    // 实现了AmqpTemplate接口
    @Resource
    RabbitTemplate rabbitTemplate;

    public void sendMessage(String name, String value) {
        // 1、有返回值....当收到结果后,才可以发送下一条数据
        Object o = amqpTemplate.convertSendAndReceive(name, value);
        // 2、无返回值....无需等待下一条数据
//        amqpTemplate.convertAndSend(name, value);
        log.info("{}队列发送消息：{}", name, value);
        log.info("{}队列发送后接收内容：{}", name, o);

    }

    /**
     * 服务提供方，采用messageid，防止重复消费
     * @param name
     * @param value
     */
    public void sendMessage2(String name, String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("message", value);

        // 设置消息内容和messageId
        Message message = MessageBuilder.withBody(jsonObject.toString().getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .setContentEncoding("UTF-8")
                .setMessageId(RandomUtil.randomString(10))
                .build();

        Object o = rabbitTemplate.convertSendAndReceive(name, message);
        System.out.println(o);
    }

}
